package stardust.core.network.protocol.http;


import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import stardust.core.network.NetworkSessionInputStream;


public class HttpResponseMeta
{

  private HttpVersion version;

  private int statusCode;

  private String description;

  private byte[] data;

  private Map<String, String> others = new Hashtable<String, String>();

  public String getResponse()
  {
    StringBuffer buff = new StringBuffer();

    buff.append(this.version).append(" ").append(this.statusCode).append(" ").append(this.description).append("\r\n");

    Iterator<String> keys = this.others.keySet().iterator();
    String key, value;

    while (keys.hasNext())
    {
      key = keys.next();
      value = this.others.get(key);

      buff.append(key).append(": ").append(value).append("\r\n");
    }

    return buff.append("\r\n").toString();
  }

  public HttpVersion getVersion()
  {
    return version;
  }

  public void setVersion(HttpVersion version)
  {
    this.version = version;
  }

  public int getStatusCode()
  {
    return statusCode;
  }

  public void setStatusCode(int statusCode)
  {
    this.statusCode = statusCode;
  }

  public String getDescription()
  {
    return description;
  }

  public void setDescription(String description)
  {
    this.description = description;
  }

  public Map<String, String> getOthers()
  {
    return others;
  }

  public byte[] getData()
  {
    return data;
  }

  public void setData(byte[] data)
  {
    this.data = data;
  }

  public static HttpResponseMeta parse(NetworkSessionInputStream reader) throws IOException
  {
    HttpResponseMeta meta = new HttpResponseMeta();
    String cmd, key, value;
    String[] tmpCmd;

    cmd = reader.readLine();

    if (cmd == null)
    {
      return null;
    }
    tmpCmd = cmd.split(" ", 3);

    try
    {
      meta.version = HttpVersion.get(tmpCmd[0]);
      meta.statusCode = Integer.parseInt(tmpCmd[1]);
      meta.description = tmpCmd[2];
    }
    catch(Exception e)
    {
      meta.version = HttpVersion.get(tmpCmd[0]);
      meta.statusCode = Integer.parseInt(tmpCmd[1]);
      meta.description = tmpCmd[1];
    }

    while ((cmd = reader.readLine()) != null && cmd.length() > 0)
    {
      tmpCmd = cmd.split(":", 2);
      key = tmpCmd[0].trim();
      value = tmpCmd[1].trim();

      // 首字母大写
      key = key.substring(0, 1).toUpperCase() + key.substring(1);

      meta.others.put(key, value);
    }

    return meta;
  }

}
